<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use app\model\{Merchant, MerchantApplication, MerchantFundFlow};
use think\facade\{Db, Log};
use think\Request;

class MerchantController extends BaseController
{
    /**
     * 获取商家列表
     */
    public function list(Request $request)
    {
        $where = [];
        
        // 游标ID
        $last_id = (int)$request->param('last_id', 0);
        if ($last_id > 0) {
            $where[] = ['id', '<', $last_id];
        }
        
        // 商家状态筛选
        if ($status = $request->param('status')) {
            $where[] = ['status', '=', $status];
        }
        
        // 关键词搜索
        if ($keyword = $request->param('keyword')) {
            $where[] = ['merchant_name|contact_name|contact_phone', 'like', "%{$keyword}%"];
        }
        
        // 每页条数
        $limit = (int)$request->param('limit', 15);
        
        $list = Merchant::where($where)
            ->with(['applications'])
            ->order('id', 'desc')
            ->limit($limit + 1)
            ->select();
            
        $has_more = false;
        if (count($list) > $limit) {
            $has_more = true;
            $list = array_slice($list->toArray(), 0, $limit);
        } else {
            $list = $list->toArray();
        }
        
        // 获取下一页的游标ID
        $next_id = 0;
        if ($has_more && !empty($list)) {
            $next_id = end($list)['id'];
        }
        
        // 统计数据
        $stats = [
            'total_count' => Merchant::where($where)->count(),
            'total_balance' => Merchant::where($where)->sum('balance'),
            'pending_count' => Merchant::where('status', 0)->count()
        ];
        
        return $this->success('获取成功', [
            'list' => $list,
            'has_more' => $has_more,
            'next_id' => $next_id,
            'stats' => $stats
        ]);
    }
    
    /**
     * 审核商家
     * @param Request $request
     * @param int $id 商家ID
     */
    public function audit(Request $request, $id)
    {
        $data = $request->post();
        $validate = $this->validate($data, [
            'status' => 'require|in:1,2',
            'remark' => 'max:255'
        ]);
        
        if($validate !== true){
            return $this->error($validate);
        }

        Db::startTrans();
        try {
            // 先查询商家是否存在
            $merchant = Merchant::where('id', $id)->find();
            if (!$merchant) {
                throw new \Exception('商家不存在');
            }
            
            // 检查商家状态
            if ($merchant->status != 0) {
                throw new \Exception('商家已审核');
            }
            
            $updateData = [
                'status' => intval($data['status']),
                'remark' => $data['remark'] ?? ''
            ];
            
            if (!$merchant->save($updateData)) {
                throw new \Exception('更新失败');
            }
            
            Db::commit();
            return $this->success('审核成功111');
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('商家审核失败：' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 禁用/启用商家
     */
    public function status(Request $request, $id)
    {
        $status = $request->post('status');
        if (!in_array($status, [1, 2])) {
            return $this->error('状态值错误');
        }
        
        Db::startTrans();
        try {
            $merchant = Merchant::find($id);
            if (!$merchant) {
                throw new \Exception('商家不存在');
            }
            
            $merchant->save([
                'status' => $status,
                'update_time' => date('Y-m-d H:i:s')
            ]);
            
            Db::commit();
            return $this->success('操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 获取商家资金流水
     */
    public function fundFlow(Request $request, $id)
    {
        $where = [
            ['merchant_id', '=', $id]
        ];
        
        // 流水类型筛选
        if ($type = $request->param('type')) {
            $where[] = ['fund_flow_type', '=', $type];
        }
        
        // 时间范围筛选
        if ($start_time = $request->param('start_time')) {
            $where[] = ['create_time', '>=', $start_time];
        }
        if ($end_time = $request->param('end_time')) {
            $where[] = ['create_time', '<=', $end_time];
        }
        
       // 每页条数
       $limit = (int)$request->param('limit', 15);
        
       $list = MerchantFundFlow::where($where)
           ->with(['applications'])
           ->order('id', 'desc')
           ->limit($limit + 1)
           ->select();
           
       $has_more = false;
       if (count($list) > $limit) {
           $has_more = true;
           $list = array_slice($list->toArray(), 0, $limit);
       } else {
           $list = $list->toArray();
       }
       
       // 获取下一页的游标ID
       $next_id = 0;
       if ($has_more && !empty($list)) {
           $next_id = end($list)['id'];
       }
       
       return $this->success('获取成功', [
           'list' => $list,
           'has_more' => $has_more,
           'next_id' => $next_id,
       ]);
    }    
    /**
     * 获取商家应用配置
     */
    public function applications($id)
    {
        $list = MerchantApplication::where('merchant_id', $id)
            ->order('id', 'desc')
            ->select();
            
        return $this->success('获取成功', $list);
    }
    
    /**
     * 获取商家详情
     * @param int $id 商家ID
     */
    public function detail(Request $request)
    {
        // 获取商家ID
        $id = $request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }

        try {
            // 查询商家信息，同时关联查询应用信息
            $merchant = Merchant::with(['applications'])->find($id);
            if (!$merchant) {
                return $this->error('商家不存在');
            }

            // 获取商家统计数据
            $stats = [
                'order_count' => \app\model\Order::where('merchant_id', $id)->count(),
                'user_count' => \app\model\User::where('merchant_id', $id)->count(),
                'today_income' => \app\model\MerchantFundFlow::where('merchant_id', $id)
                    ->whereDay('create_time')
                    ->where('fund_flow_type', 'in', [3, 5]) // 订单支付和分佣收入
                    ->sum('fund_flow_amount'),
                'total_income' => \app\model\MerchantFundFlow::where('merchant_id', $id)
                    ->where('fund_flow_type', 'in', [3, 5])
                    ->sum('fund_flow_amount')
            ];

            $data = array_merge($merchant->toArray(), ['stats' => $stats]);
            
            return $this->success('获取成功', $data);
        } catch (\Exception $e) {
            Log::error('获取商家详情失败：' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
} 